<template>
    <el-form :model="spuInfo" label-width="100px">
        <el-form-item label="SPU名称">
            <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
            <el-select v-model="spuInfo.tmId" placeholder="请选择品牌">
                <el-option
                    :label="tm.tmName"
                    :value="tm.id"
                    v-for="tm in trademarkList"
                    :key="tm.id"
                ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="SPU描述" rows="4" v-model="spuInfo.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
            <!-- 
                :file-list="spuImageList"               需要渲染的图片,是数组
                :on-preview="handlePictureCardPreview"  放大镜的预览效果
                :on-remove="handleRemove"               删除图片
                list-type="picture-card"                图片集
                :on-success="handlePictureSuccess"      添加图片
            -->
            <el-upload
                action="/dev-api/admin/product/fileUpload"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :file-list="spuImageList"
                :on-success="handlePictureSuccess"
            >
                <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
        </el-form-item>
        <el-form-item label="销售属性">
            <el-select
                v-model="spuSaleAttrName"
                :placeholder="unSelectAttrList.length > 0 ? `还有${unSelectAttrList.length}个未选中` : '都选中了'"
            >
                <el-option
                    :label="unSelectAttr.name"
                    :value="`${unSelectAttr.id}:${unSelectAttr.name}`"
                    v-for="unSelectAttr in unSelectAttrList"
                    :key="unSelectAttr.id"
                ></el-option>
            </el-select>
            <el-button
                type="primary"
                icon="el-icon-plus"
                @click="addSpuAttr"
                :disabled="!spuSaleAttrName"
            >添加销售属性</el-button>
            <el-table :data="spuInfo.spuSaleAttrList" border style="width: 100%">
                <el-table-column type="index" align="center" label="序号" width="80"></el-table-column>
                <el-table-column prop="saleAttrName" label="属性名" width="150"></el-table-column>
                <el-table-column prop="prop" label="属性值名称列表" width="width">
                    <template slot-scope="{row}">
                        <!-- <el-tag
                            type="primary"
                            v-for="spuSaleAttrValue in row.spuSaleAttrValueList"
                            :key="spuSaleAttrValue.id"
                        ></el-tag>-->
                        <!-- @close="handleClose(tag)" -->
                        <el-tag
                            :key="spuSaleAttrValue.id"
                            v-for="spuSaleAttrValue in row.spuSaleAttrValueList"
                            closable
                            :disable-transitions="false"
                        >{{ spuSaleAttrValue.saleAttrValueName }}</el-tag>
                        <!-- 
                            row.isEdit:
                                true    显示的input
                                false   显示的button
                        -->
                        <el-input
                            v-model="row.saleAttrValueName"
                            v-if="row.isEdit"
                            class="input-new-tag"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(row)"
                            @blur="handleInputConfirm(row)"
                        ></el-input>
                        <el-button
                            @click="showInput(row)"
                            v-else
                            class="button-new-tag"
                            size="small"
                        >添加</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="prop" label="操作" width="150">
                    <template slot-scope="{row,$index}">
                        <el-tooltip effect="dark" content="删除" placement="top">
                            <el-button
                                type="danger"
                                size="mini"
                                icon="el-icon-delete"
                                @click="delAttrValue(spuInfo.spuSaleAttrList, $index)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
export default {
    name: 'Spuform',
    data() {
        return {
            /* 
                收集一级销售属性
             */
            spuSaleAttrName: "",

            dialogImageUrl: '',
            dialogVisible: false,

            trademarkId: '',    //等下用来作为收集数据使用
            /* 获取所有的品牌信息 */
            trademarkList: [],
            /* 所有的销售属性 */
            baseSaleAttrList: [],

            /* 返回的是 获取指定SPU的id对应的图片列表 */
            spuImageList: [],

            /* spuInfo */
            spuInfo: {
                category3Id: 0,
                description: "",
                // id: 0,
                spuImageList: [
                    // {
                    //     "id": 0,
                    //     "imgName": "string",
                    //     "imgUrl": "string",
                    //     "spuId": 0
                    // }
                ],
                tmId: '',
                spuName: "",
                spuSaleAttrList: [
                    // {
                    //     baseSaleAttrId: 0,
                    //     saleAttrName: "",
                    //     spuSaleAttrValueList: [
                    //         // {
                    //         //     "baseSaleAttrId": 0,
                    //         //     "saleAttrName": "string",
                    //         //     "saleAttrValueName": "string",
                    //         // }
                    //     ]
                    // }
                ],
            }
        };
    },
    methods: {
        /* 添加图片完成 */
        handlePictureSuccess(res, file, fileList) {
            /* 
                两种方法都可以收集图片的路径
             */
            // console.log(res.data, file.response.data);
            this.spuImageList = fileList
        },
        /* 在图片集当中删除图片 */
        handleRemove(file, fileList) {
            /* 
                file        删除的那个图片
                fileList    删除完毕之后,剩下那几张图片
            */
            // console.log(file, fileList);
            this.spuImageList = fileList;
        },
        /* 放大镜的预览效果 */
        handlePictureCardPreview(file) {
            /* dialog显示的那张图片 */
            this.dialogImageUrl = file.url;
            /* 使用使用dialog弹出 */
            this.dialogVisible = true;
        },

        /* 父组件点击的是添加按钮,在这个函数里面发送ajax请求,发送的是两条 */
        async addSpuform(category3Id) {
            this.spuInfo.category3Id = category3Id
            /* 获取所有的品牌信息 */
            // http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
            const trademarkListResult = await this.$API.trademark.getTrademarkList();
            if (trademarkListResult.code == 200 || trademarkListResult.code === 20000) {
                this.trademarkList = trademarkListResult.data
            }
            /* 获取所有的销售属性 */
            // http://localhost:9529/dev-api/admin/product/baseSaleAttrList
            const baseSaleAttrListResult = await this.$API.spu.getSaleAttrList();
            if (baseSaleAttrListResult.code === 200 || trademarkListResult.code === 20000) {
                this.baseSaleAttrList = baseSaleAttrListResult.data
            }
        },
        /* 父组件点击的是修改按钮,在这个函数里面发送ajax请求,发送的是四条 */
        async updateSpufrom(row) {
            /* 获取所有的品牌信息 */
            // http://localhost:9529/dev-api/admin/product/baseTrademark/getTrademarkList
            const trademarkListResult = await this.$API.trademark.getTrademarkList();
            if (trademarkListResult.code == 200 || trademarkListResult.code === 20000) {
                this.trademarkList = trademarkListResult.data
            }
            /* 获取所有的销售属性 */
            // http://localhost:9529/dev-api/admin/product/baseSaleAttrList
            const baseSaleAttrListResult = await this.$API.spu.getSaleAttrList();
            if (baseSaleAttrListResult.code === 200 || trademarkListResult.code === 20000) {
                this.baseSaleAttrList = baseSaleAttrListResult.data
            }
            // 根据id获取SPU详情信息
            // http://localhost:9529/dev-api/admin/product/getSpuById/6525
            const spuInfoResult = await this.$API.spu.get(row.id);
            if (spuInfoResult.code === 200 || spuInfoResult.code === 20000) {
                this.spuInfo = spuInfoResult.data
            }
            // 获取指定SPU的id对应的图片列表
            // http://localhost:9529/dev-api/admin/product/spuImageList/6525
            const spuImageListResult = await this.$API.sku.getSpuImageList(row.id)
            if (spuImageListResult.code === 200 || spuImageListResult.code === 20000) {
                // this.spuImageList = spuImageListResult.data
                let spuImageList = spuImageListResult.data
                spuImageList.forEach(item => {
                    /* .语法
                            无则添加,有则修改
                    */
                    item.name = item.imgName
                    item.url = item.imgUrl
                })
                this.spuImageList = spuImageList
            }
        },

        /* 添加一级销售属性 */
        addSpuAttr() {
            /* 
                1.拆分
                2.创建一个对象
                    包含
                        baseSaleAttrId
                        saleAttrName
                        spuSaleAttrValueList
                3.往spuInfo中的spuSaleAttrList添加数据
             */
            let [baseSaleAttrId, saleAttrName] = this.spuSaleAttrName.split(":")
            let obj = {
                baseSaleAttrId,
                saleAttrName,
                spuSaleAttrValueList: []
            }
            this.spuInfo.spuSaleAttrList.push(obj)

            /* 清空一级销售属性数据 */
            this.spuSaleAttrName = ""
        },
        showInput(row) {
            // row.isEdit = true
            this.$set(row, 'isEdit', true)

            /* 获取光标 */
            this.$nextTick(() => {
                this.$refs.saveTagInput.focus();
            })
        },

        /*  */
        handleInputConfirm(row) {
            // {
            //     "baseSaleAttrId": 0,
            //     "saleAttrName": "string",
            //     "saleAttrValueName": "string",
            // }
            let { baseSaleAttrId, saleAttrName, saleAttrValueName } = row
            if (!saleAttrValueName.trim()) {
                row.saleAttrValueName = "";
                row.isEdit = false
                return
            }
            /* 用户不能输入重复的数据 */
            let isRepeat = row.spuSaleAttrValueList.some(item => item.saleAttrValueName == saleAttrValueName)
            if (isRepeat) {
                this.$message.warning("输入的数据已存在!");
                row.saleAttrValueName = "";
                row.isEdit = false
                return;
            }
            let obj = {
                baseSaleAttrId,
                saleAttrName,
                saleAttrValueName
            }
            row.spuSaleAttrValueList.push(obj)

            row.saleAttrValueName = "";
            row.isEdit = false
        },
        /* 点击保存,发送ajax */
        async save() {
            /* 处理图片 */
            this.spuImageList.forEach(item => {
                item.imgName = item.name
                item.imgUrl = item.response ? item.response.data : item.imgUrl
            })

            this.spuInfo.spuImageList = this.spuImageList
            try {
                // 打印data
                // console.log(this._data);

                /* 
                    data的初始化
                */
                // console.log(this.$options.data());

                const result = await this.$API.spu.addUpdate(this.spuInfo)
                if (result.code === 200 || result.code == 20000) {
                    /* 通知一下他父组件,告诉父组件重新获取一下数据 */
                    if (this.spuInfo.id) {
                        this.$emit("geigemingzi", true)
                    } else {
                        this.$emit("geigemingzi", false)
                    }
                    /* 
                        将后面的覆盖点前面的
                    */
                    Object.assign(this._data, this.$options.data());

                    this.$emit('update:isShowSpuList', false)
                } else {
                    this.$message.error("请求失败,请联系管理员!")
                }
            } catch (error) {
                this.$message.error("请求异常,请稍后再试")
            }
        },
        cancel() {
            Object.assign(this._data, this.$options.data());
            this.$emit('update:isShowSpuList', false)
        },
        delAttrValue(spuSaleAttrList, index) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                spuSaleAttrList.splice(index, 1)
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    },
    /* 使用计算属性计算出销售属性为选择的属性 */
    computed: {
        unSelectAttrList() {
            // this.baseSaleAttrList   //所有的销售属性
            // this.spuInfo.spuSaleAttrList    //spuInfo中的销售属性
            // return this.baseSaleAttrList.filter(item => {
            //     return this.spuInfo.spuSaleAttrList.every(item1 => {
            //         return item.name != item1.saleAttrName
            //     })
            // })
            let spuSaleAttr = this.spuInfo.spuSaleAttrList || []
            return this.baseSaleAttrList.filter(item => spuSaleAttr.every(item1 => item.name != item1.saleAttrName))
        }
    }
};
</script>

<style>
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>